<template>
  <div style="width: 100%;" :class="records.length==0&&isCenter?'activeWid':''">
    <el-table :data="records" style="width: 100%" v-loading="loading" :class="isHight?'mytable':''"
      element-loading-svg-view-box="-10, -10, 50, 50" element-loading-text="奋力加载中" :row-key="rowKey" ref="selectTable"
      :row-class-name="tableRowClassName" :element-loading-svg="Loading"
      element-loading-background="rgba(255, 255, 255, 1)" @select="select" @select-all="selectAll"
      :show-overflow-tooltip="true">
      <template #empty v-if="loading == false">
        <div class="center">
          <img src="../../assets/blank.png" class="image" />
          <p>暂时还没有内容呢...</p>
        </div>
      </template>
      <el-table-column v-if="isSelection" :reserve-selection="true" :selectable="selectable" type="selection"
        width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="100" fixed="left" align="center" v-if="serial">
        <template #default="{ $index }">
          <span v-if="$index==records.length-1&&isTotal">总计</span> 
        </template>
      </el-table-column>
      <el-table-column :label="item.label" :min-width="item.width" :align="item.align ? item.align : 'left'"
        v-for="(item, index) in fields" :key="index" :property="item.prop">
        <template #default="scope">
          <template v-if="item.children && item.children.length">
            <el-table-column v-for="(column, index1) in item.children" :key="index1" :property="column.prop"
              :align="column.align ? column.align : 'left'" :min-width="column.width" :label="column.label">
              <template v-if="column.children && column.children.length">
            <el-table-column v-for="(column1, index2) in column.children" :key="index2" :property="column1.prop"
              :align="column1.align ? column1.align : 'left'" :min-width="column1.width" :label="column1.label">
            </el-table-column>
          </template>
            </el-table-column>
          </template>
          <span v-if="!$slots[item.prop]">
            {{
      item.filter
        ? item.filter(scope.row[item.prop])
        : scope.row[item.prop]
    }}
          </span>
          <slot v-else :name="item.prop" :row="scope.row" :index="scope.$index"></slot>
        </template>
        <template #header>
          {{ item.label }}
          <img src="../../assets/screen.svg" alt="" v-if="item.screen && !item.isOrderBy" class="screen"
            @click="screenChange(item.prop, index)">
          <img src="../../assets/screen1.svg" alt="" v-if="item.screen && item.isOrderBy" class="screen"
            @click="screenChange('', index)">
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" :align="'left'" :width="width" v-if="handle">
        <template v-slot="{ row, column, $index }">
          <slot name="operation" :row="row" :column="column" :$index="$index"></slot>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination" v-if="isPaginationShow">
      <el-pagination v-model:current-page="model.pageNum" v-model:page-size="model.pageSize"
        :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
         @change="handleCurrentChange" />
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, watch, getCurrentInstance, onMounted, ref, nextTick } from "vue"
import { Loading } from '@element-plus/icons-vue'
type dataType = {
  total: number;
  model: modeltype;
  loading: boolean;
  records: any;
  echoList: any
}
type modeltype = {
  pageNum: number;
  pageSize: number;
}
type item = {
  label: string,
  width: string,
  align: string,
  prop: string,
  children: any,
  filter: any,
  screen: null | boolean
  isOrderBy: null | boolean
}
export default defineComponent({
  name: "App",
  props: {
    //表头
    fields: { type: Array as () => item[], default: [] },
    // arr: {//需要用到v-slot的字段，vue3中没有$scopedSlots
    //   type: Array,
    //   default: [],
    // },
    defaultList: {
      type: Array,
      default: [],
    },
    //是否显示多选框
    isSelection: {
      type: Boolean,
      default: false,
    },
    //是否显示序号
    serial: {
      type: Boolean,
      default: true,
    },
    //是否显示操作栏
    handle: {
      type: Boolean,
      default: true,
    },
    //是否显示最小高度
    isHight: {
      type: Boolean,
      default: true,
    },
    width: {
      type: String,
      default: "100",
    },
    rowKey: {
      type: String,
      default: "id",
    },
    //是否显示分页
    isPaginationShow: {
      type: Boolean,
      default: true,
    },
    values: {
      type: Object,
      default: {},
    },
    api: {
      type: String,
      default: null,
    },
    ergodicData: {
      type: Function
    },
    type:{
      type: String,
      default: ''
    },
    isTotal:{
      type: Boolean,
      default: false,
    },
    isCenter:{
      type: Boolean,
      default: true,

    }
  },
  setup(props: any, { emit }: any) {
    const data: dataType = reactive({
      total: 0,
      model: {
        pageNum: 1,
        pageSize: 10,
      },
      loading: true,
      records: [],
      echoList: []
    });
    const currentInstance = getCurrentInstance()//获取全局挂载实例
    onMounted(() => {
      methods.init()
    })
    const selectTable = ref()
    const methods = {
      //返回值用来决定这一行的 CheckBox 是否可以勾选
      selectable(row: any, index: number) {
       if(props.type){
         let arr =data.records.filter(item=>{
          return item[props.type]==0
         })
         let list=arr.map(item=>{
          return item.id
         })
        return list.includes(row.id);
        //    emit('selectable',row,index)
       }else{
        return true
       }
      },
      //当用户手动勾选数据行的 Checkbox 时触发的事件
      select(selection: any, row: any) {
        emit("selecSelection", selection);
      },
      //当用户手动勾选全选 Checkbox 时触发的事件
      selectAll(selection: any) {
        emit("selecSelection", selection);
      },
      // 请求表格数据
      init() {
        data.loading = true
        const val = Object.assign(props.values, data.model);
        if (!props.api) {
          data.loading = false
          return
        }
        let fun = currentInstance?.appContext.config.globalProperties.$tablejs[props.api]
        fun(val)
          .then((res: any) => {
            console.log(res);
            if (props.ergodicData) {
              data.records = props.ergodicData(res.records);
            } else {
              data.records = res.records;
            }
            data.loading = false;
            data.total = res.total;
            emit("init", res);
            if (data.echoList.length > 0) {
              setTimeout(() => {

                methods.echo(data.echoList)

              }, 600);
            }
          })
          .catch((err: any) => {
            data.loading = false;
          });
      },
      //条数改变触发
      handleSizeChange(number: number) {
        data.loading = true
        data.model.pageSize = number;
        methods.init();
      },
      //页数改变触发
      handleCurrentChange(currentPage: number, pageSize: number) {
        data.loading = true
        data.model.pageNum = currentPage;
        if(pageSize){
          data.model.pageSize = pageSize;
        }
        methods.init();
      },
      resettingTable(values: any) {
        data.model.pageNum = 1
        data.loading = true
        const val = Object.assign(values, data.model);
        if (!props.api) return
        let fun = currentInstance?.appContext.config.globalProperties.$tablejs[props.api]
        fun(val)
          .then((res: any) => {
            if (props.ergodicData) {
              data.records = props.ergodicData(res.records);
            } else {
              data.records = res.records;
            }
            data.loading = false;
            data.total = res.total;
            emit("init", res);
          })
          .catch((err: any) => {
            data.loading = false;
          });
      },
      echo(list: any) {
        data.echoList = list
        nextTick(() => {
          data.records.map((row: any) => {
            if (list.some((item1: any) => row.id == item1.empId)) {
              selectTable.value!.toggleRowSelection(row, true)
            }
          })
        })
      },
      clearSelection() {
        selectTable.value!.clearSelection()
      },
      screenChange(prop: string, index) {
        emit("screenChange", prop, index);
      },
      tableRowClassName(row: any,) {
        if (row.rowIndex % 2 != 1) {
          return 'warningRow'
        } else {
          return ''
        }

      }
      // questionIcon(e:any){
      //   if(e.column.label.length * 14 > 50){
      //     return h(ElTooltip, { placement: 'top' }, {
      //         default: () => e.column.label.slice(0, 10) + '...',
      //         content: () => e.column.label
      //       });
      //   }else{
      //     return e.column.label
      //   }
      // }
    };
    // 监听props的变化
    watch(() => props.defaultList, (newValue, oldValue) => {
      if (newValue) {
        data.records = newValue
        data.loading=false
      }
    }, { immediate: true, deep: true });
    return {
      ...methods,
      ...toRefs(data),
      Loading, selectTable
    };
  },
});
</script>
<style lang="scss" scoped>
.image {
  height: 150px;
}

.pagination {
  width: 100%;
  background: #fff;
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.mytable {
  min-height: 300px;
}

.screen {
  cursor: pointer;
}

.active {
  color: #1890ff;
}
</style>
<style lang="scss">
.el-pagination {
  .el-select {
    width: 128px !important;
  }

  .el-input {
    width: 56px !important;
  }
}

.warningRow {
  background-color: #F7F7F7 !important;
}
.activeWid{
  .el-table__header,.el-table__empty-block{
    width: auto !important;
  }
  .el-table__body{
  width: auto !important;
}
}
</style>